/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sdc.event;

import sdc.net.server.appli.ApplicationServer;
import sdc.net.server.appli.ApplicationServerManager;
import sdc.Address;
import sdc.component.type.ComponentType;
import sdc.net.server.comp.ComponentServer;
import sdc.net.server.comp.ComponentServerManager;
import sdc.utility.LoggingManager;
import java.util.Map.Entry;
import java.util.logging.Level;

/**
 *
 * @author yokoe
 */
public class SamplingEvent extends Event{

    private final double t = 1.0;

    private final int mode;

    public SamplingEvent(double eventTime, int mode) {
        super(eventTime);
        this.mode = mode;
    }

	@Override
    public void fire() {
            switch(mode) {
                case 0:
                    tat();
                    break;
                case 1:
                    sla();
                    break;
            }
    }

        private void tat() {
        double TAT = 0.0;
        int i = 0;
        for (Entry<Address, ApplicationServer> app : ApplicationServerManager.INSTANCE.getApplicationServerMap().entrySet()) {
            double TATsum = 0.0;
            for (Entry<ComponentType, Address> entry : app.getValue().getUseComponentMap().entrySet()) {
                TATsum += ComponentServerManager.INSTANCE.get(entry.getValue()).getTAT(entry.getKey());
            }
            TAT += TATsum / 3.0;
            i++;
        }

        LoggingManager.logging(Level.INFO, "Current TAT " + (TAT / (double) i), new Throwable());

        EventQueue eventQueue = EventQueue.INSTANCE;
        eventQueue.addEvent(new SamplingEvent(eventQueue.getCurrentTime() + t, mode));
    }

        private void sla() {
            int total = 0;
            int notMeet = 0;
            for(ComponentServer server : ComponentServerManager.INSTANCE.getList()) {
                for(ComponentType type : server.getRequestNumMap().keySet()) {
                    total++;
                    if(server.getEwma(type) > type.getSLA()) {
                        notMeet++;
                    }
                }
            }
            LoggingManager.logging(Level.INFO, "SLA rate " + ((double)notMeet / total), new Throwable());

            EventQueue eventQueue = EventQueue.INSTANCE;
            eventQueue.addEvent(new SamplingEvent(eventQueue.getCurrentTime() + t, mode));
        }
}
